﻿#ifndef FRAMERENDERER_H
#define FRAMERENDERER_H

#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLTexture>
#include <QOpenGLShader>
#include "AudioPlayer.h"
#include <QOpenGLShaderProgram>
#include <QtQuick/QQuickItem>
#include <QtQuick/QQuickWindow>

extern "C"
{
#include <libavutil/avutil.h>
}

class GLRenderer : public QObject, protected QOpenGLFunctions
{
    Q_OBJECT

public:
    explicit GLRenderer(QObject* parent = nullptr);

    virtual ~GLRenderer();

    void setFrame(AVFrame* frame);

    void resizeGL(int w, int h);

    void initializeGL();

    QQuickWindow* window() const { return m_window; }
    void setWindow(QQuickWindow* window);

    void clearRenderContext();

public slots:
    void init();

    void paintFrame();

private:

    void deliverFrame(AVFrame* frame);

    void makeYUVTextures(int yl, int ul, int vl, int h);

    AVFrame* m_curFrame = nullptr;
    AVFrame* m_nextFrame = nullptr;

    GLuint m_yTex = 0, m_uTex = 0, m_vTex = 0;

    GLuint m_vbo = 0;

    // 着色器程序
    QOpenGLShaderProgram* m_shaderProgram = nullptr;

    QQuickWindow* m_window = nullptr;

    int m_viewportWidth = 0;
    int m_viewportHeight = 0;
};


class FrameRenderer : public QQuickItem 
{
    Q_OBJECT
    QML_ELEMENT

public:
    FrameRenderer();

    void setFrame(AVFrame* frame) {
        m_glRenderer->setFrame(frame);
    }

public slots:
    void sync();
    void cleanup();
    void handleWindowChanged(QQuickWindow* window);

private:
    void releaseResources() override;

    GLRenderer *m_glRenderer = nullptr;
}
;

#endif // FRAMERENDERER_H
